/*
 * Created on 2005-8-23
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.jedi;

import java.util.HashMap;

import com.tss.util.TSSDate;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class KeyGen {
	private static KeyGen keygen = null;
	private static Object initLock = new Object();
	private HashMap uniqueIDCounters;
	private Keyer defaultKey = null;
	
	public KeyGen() {
		uniqueIDCounters = new HashMap();
		try {
			uniqueIDCounters.put("MSG_KEY", new Keyer(0));
			defaultKey = new Keyer(0);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String nextID(String type) {
		init();
		return keygen.nextKeyID(type.trim().toUpperCase());
	}
	
	private static void init() {
		if (keygen == null) {
			synchronized(initLock) {
				if (keygen == null) {
					keygen = new KeyGen();
				}
			}
		}
	}
	
	public String nextKeyID(String counterName) {
		Keyer keyer = (Keyer)uniqueIDCounters.get(counterName);
		if (keyer==null) return defaultKey.next();
		return keyer.next();
	}
	
	private final class Keyer {
		private long count;
		public Keyer(long currentCount) {
			count = currentCount;
		}
		public final synchronized String next() {
			String r = "0000000000" + (++count);
			if (count >= 99995) count = 0;
			return TSSDate.fullTimeNoFormat() + r.substring(r.length() - 5);
		}
	}
}
